<template>
  <BasicModal
    v-bind="$attrs"
    destroyOnClose
    @register="registerDrawer"
    showFooter
    title="事件定义"
    width="70%"
    :minHeight="300"
    :showCancelBtn="false"
    @ok="handleSubmit"
  >
    <!--  <FormTitle text="基础设置" class="ml-4" /> -->

    <div v-if="formConfig.currentItem">
      <Dropdown @menu-event="handleAddEvent" :trigger="['click']" :dropMenuList="eventList">
        <a-button type="primary"> 添加事件 </a-button>
      </Dropdown>
      <div class="event-config mt-4" v-if="!isEmpty(eventObj)">
        <Collapse v-model:activeKey="activeKey" expandIconPosition="end">
          <CollapsePanel v-for="item in (eventObj as any)" :header="item.text" :key="item.event">
            <template #extra>
              <a-button type="link" size="small" @click.stop="handleFunc(item)">
                添加方法
              </a-button>
              <a-button type="link" @click="handleDelEvent(item)" danger size="small"
                >删除
              </a-button>
            </template>

            <div v-if="item.funcList">
              <div class="func-item flex" v-for="(func, idx) in item.funcList" :key="func.label">
                <div class="flex-1">{{ func.label }}</div>
                <div class="ml-2">
                  <a-button type="link" size="small" @click.stop="handleFunc(func, true)">
                    编辑
                  </a-button>
                  <a-button
                    type="link"
                    @click="handleDelFunc(item.funcList, idx)"
                    danger
                    size="small"
                    >删除
                  </a-button>
                </div>
              </div>
            </div>
          </CollapsePanel>
        </Collapse>
      </div>
      <FormEventFuncConfig @register="registerFuncModal" />
    </div>
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, ref, unref, watch } from 'vue';
  import { Collapse } from 'ant-design-vue';
  import { ComponentTypeEnum } from '/@/components/ModelTable/src/types';

  import FormEventFuncConfig from './FormEventFuncConfig.vue';
  import { cloneDeep } from 'lodash-es';

  import { isEmpty } from '/@/utils/is';
  import {
    Form_Event_List,
    Event_List,
    Event_Focus_Blur_List,
    Event_Upload_BTN_List,
    Event_Upload_Drag_List,
    Event_Search_List,
  } from '/@/views/config-center/model-design/components/consts';
  import { CompType } from '/@/components/Upload';

  import { DICT } from '/@/enums/dict';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { Dropdown } from '/@/components/Dropdown';
  import { useModal } from '/@/components/Modal';
  import { useFormDesignState } from '../../../hooks/useFormDesignState';

  // import { useMessage } from '/@/hooks/web/useMessage';
  const hasComEventType = (val) =>
    [
      ComponentTypeEnum.Input,
      ComponentTypeEnum.InputNumber,
      ComponentTypeEnum.ApiSelect,
      ComponentTypeEnum.ApiTreeSelect,
      ComponentTypeEnum.InputTextArea,
      ComponentTypeEnum.InputPassword,
      ComponentTypeEnum.DatePicker,
      ComponentTypeEnum.TimePicker,
      ComponentTypeEnum.TimeRangePicker,
      ComponentTypeEnum.RangePicker,
    ].includes(val);
  export default defineComponent({
    name: 'FormFieldEventConfig',
    components: {
      BasicModal,
      Dropdown,
      Collapse,
      CollapsePanel: Collapse.Panel,
      FormEventFuncConfig,
    },
    emits: ['register'],
    setup() {
      const { formConfig } = useFormDesignState();
      // const { createMessage } = useMessage();
      const eventObj = ref<Indexable>({});

      const isFormEvent = ref(false);

      const [registerFuncModal, { openModal: funcModal }] = useModal();

      const activeKey = ref<string[]>([]);
      const [registerDrawer, { setModalProps, closeModal }] = useModalInner(
        async (data: Indexable) => {
          activeKey.value = [];
          setModalProps({ confirmLoading: false });
          init(data);
        },
      );

      const eventList = ref<any[]>([]);

      watch(
        () => activeKey.value,
        (v) => {
          // 禁止添加重复事件
          eventList.value.forEach((el) => {
            el.disabled = v.includes(el.event);
          });
        },
        { deep: true },
      );

      async function init({ isForm }: Indexable) {
        const currentEvent = isForm ? formConfig.value.event : formConfig.value.currentItem!.event;

        eventObj.value = cloneDeep(currentEvent || {});

        isFormEvent.value = isForm;
        Object.keys(eventObj.value).forEach((key) => {
          activeKey.value.push(key);
        });
        setEventList();
      }

      function setEventList() {
        const Event_Delete_List = [
          {
            text: '删除',
            event: 'onDelete',
            disabled: false,
          },
        ];
        const Event_Click_List = [
          {
            text: '点击',
            event: 'onClick',
            disabled: false,
          },
        ];

        const { componentType, componentProps: { compType = 2 } = {} } =
          formConfig.value.currentItem! || {};

        let list: any[] = cloneDeep(Event_List);

        if (hasComEventType(componentType)) {
          list = list.concat(cloneDeep(Event_Focus_Blur_List));

          if (
            [ComponentTypeEnum.ApiSelect, ComponentTypeEnum.ApiTreeSelect].includes(componentType)
          ) {
            list = list.concat(cloneDeep(Event_Search_List));
          }
        }

        if (componentType === ComponentTypeEnum.Upload) {
          if (compType === CompType.BUTTON) {
            list = cloneDeep(Event_Upload_BTN_List);
          } else {
            list = cloneDeep(Event_Upload_Drag_List);
          }
        }

        if (componentType === ComponentTypeEnum.SubTable) {
          list = list.concat(Event_Delete_List);
        }

        if (unref(isFormEvent)) {
          list = cloneDeep(Form_Event_List);
        }

        if (componentType === ComponentTypeEnum.HButton) {
          list = cloneDeep(Event_Click_List);
        }

        if (componentType === ComponentTypeEnum.DatePicker) {
          list = cloneDeep(Event_Click_List);
        }

        eventList.value = list;
      }
      async function handleSubmit() {
        if (isFormEvent.value) {
          formConfig.value.event = eventObj.value;
        } else {
          formConfig.value.currentItem!.event = eventObj.value;
        }
        closeModal();

        activeKey.value = [];
      }

      const handleAddEvent = (data) => {
        data.disabled = true;

        activeKey.value.push(data.event);
        eventObj.value[data.event] = data;
      };

      const handleFunc = (record: Indexable, isUpdate = false) => {
        if (!isUpdate && !record.funcList) {
          record.funcList = [];
        }

        funcModal(true, {
          isUpdate,
          record,
        });
      };

      const handleDelEvent = (data: any) => {
        data.disabled = false;
        const idx = activeKey.value.findIndex((el) => el === data.event);
        activeKey.value.splice(idx, 1);
        delete eventObj.value[data.event];
      };
      const handleDelFunc = (item: any[], idx: number) => {
        item.splice(idx, 1);
      };

      return {
        DICT,
        formConfig,
        activeKey,
        registerFuncModal,
        eventList,
        eventObj,
        isEmpty,
        registerDrawer,
        handleSubmit,
        handleAddEvent,
        handleFunc,
        handleDelEvent,
        handleDelFunc,
      };
    },
  });
</script>
